#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use tauri::{GlobalShortcutManager, WindowBuilder};
use std::process::Command;
use tauri::api::path::config_dir;
use std::fs;
use std::path::Path;
use tauri::command;
// use tauri::api::shell::open;


fn main() {
    tauri::Builder::default()
        .setup(|app| {
            let handle = app.handle();

            // 获取全局快捷键管理器
            let mut shortcut_manager = handle.global_shortcut_manager();
             // 注册全局快捷键 Command + ,
             shortcut_manager
             .register("CommandOrControl+,", move || {
                 // 创建新窗口，显示 settings 页面
                 let _ = WindowBuilder::new(
                     &handle,
                     "settings",  // 窗口标识符
                     tauri::WindowUrl::App("settings".into())  // 指定新的设置页面 URL
                 )
                 .title("Settings")
                 .inner_size(800.0, 400.0)  // 设置窗口大小
                 .build();
             })
             .expect("Failed to register global shortcut");

            Ok(())
        })
        .invoke_handler(tauri::generate_handler![run_python_script,run_python_script_common,run_python_script_json,run_python_script_example,get_config_dir,show_in_finder])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}


// 执行Python脚本
#[tauri::command]
fn run_python_script(input: String) -> String {
  let output = Command::new("python3")
    .arg("/Users/kyren/Developer/pytest/script.py")
    .arg(&input)  // 传递参数给Python脚本
    .output()
    .expect("failed to execute process");
  
  let stdout = String::from_utf8_lossy(&output.stdout).to_string();
  
  // 打印Python脚本的输出到Tauri的控制台
  println!("Python script output: {}", stdout);
  
  stdout
}


#[tauri::command]
fn run_python_script_json(input: String) -> String {
    // 获取配置目录并构建Python脚本路径
    let pyextension_dir = get_config_dir();
    let script_path = Path::new(&pyextension_dir).join("PluginManager.py");

    // 检查脚本是否存在
    if !script_path.exists() {
        return format!("Python script not found at path: {}", script_path.display());
    }

    // 执行Python脚本
    let output = Command::new("python3")
        .arg(script_path.to_str().unwrap())
        .arg(&input)  // 传递参数给Python脚本
        .output();

    // 如果执行过程中发生错误
    let output = match output {
        Ok(output) => output,
        Err(err) => return format!("Failed to execute process: {}", err),
    };

    // 将输出转换为字符串
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();

    // 打印Python脚本的输出到Tauri的控制台
    println!("Python script output: {}", stdout);
    if !stderr.is_empty() {
        println!("Python script stderr: {}", stderr);
    }

    stdout
}


#[command]
fn run_python_script_common(pyfilename:String,input: String) -> String {
    // 获取配置目录并构建Python脚本路径
    let pyextension_dir = get_config_dir()+"/plugins";
    let script_path = Path::new(&pyextension_dir).join(&pyfilename);

    // 检查脚本是否存在
    if !script_path.exists() {
        return format!("Python script not found at path: {}", script_path.display());
    }else {
        println!("script_path:{}",script_path.display());
    }


    // 执行Python脚本
    let output = Command::new("python3")
        .arg(script_path.to_str().unwrap())
        .arg(&input)  // 传递参数给Python脚本
        .output();

    // 如果执行过程中发生错误
    let output = match output {
        Ok(output) => output,
        Err(err) => return format!("Failed to execute process: {}", err),
    };

    // 将输出转换为字符串
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();

    // 打印Python脚本的输出到Tauri的控制台
    println!("Python script output: {}", stdout);
    if !stderr.is_empty() {
        println!("Python script stderr: {}", stderr);
    }

    stdout
}





#[tauri::command]
fn run_python_script_example(input: String) -> String {
    // 获取配置目录并构建Python脚本路径
    let pyextension_dir = get_config_dir();
    // let script_path = Path::new(&pyextension_dir).join(input);
    let script_path = Path::new(&pyextension_dir).join("PluginManager.py");
    // 检查脚本是否存在
    if !script_path.exists() {
        return format!("Python script not found at path: {}", script_path.display());
    }

    // 执行Python脚本
    let output = Command::new("python3")
        .arg(script_path.to_str().unwrap())
        .arg(&input)  // 传递参数给Python脚本
        .arg("example")  // 传递参数给Python脚本
        .output();

    // 如果执行过程中发生错误
    let output = match output {
        Ok(output) => output,
        Err(err) => return format!("Failed to execute process: {}", err),
    };

    // 将输出转换为字符串
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();

    // 打印Python脚本的输出到Tauri的控制台
    println!("Python script output: {}", stdout);
    if !stderr.is_empty() {
        println!("Python script stderr: {}", stderr);
    }

    stdout
}




#[tauri::command]
fn get_config_dir() -> String {
    // 处理Option<String>，为config_dir提供默认值
    let config_dir = config_dir().map_or_else(
        || String::from("/default/path/"),  // 如果是None，返回默认路径
        |path| path.to_str().unwrap().to_string()  // 如果有值，转换为String
    );
    // 拼接路径
    let extensionpath = format!("{}{}", config_dir, "/com.text.ease/Extensions");

    // 创建目录，如果不存在
    let path: &Path = Path::new(&extensionpath);
    if !path.exists() {
        if let Err(e) = fs::create_dir_all(path) {
            eprintln!("Failed to create directory: {}", e); // 打印错误信息
        } else {
            println!("Directory created successfully: {}", extensionpath);
        }
    } else {
        println!("Directory already exists: {}", extensionpath);
    }
    
    // 打印路径
    println!("extensionpath: {}", extensionpath);
    // 返回最终路径
    return extensionpath;
}


#[command]
fn show_in_finder()  {
    let dirpath = get_config_dir();
    Command::new("open")
    .args(["-R", &dirpath])
    .spawn()
    .unwrap();
}
